/**
 * Created by chenxq on 2017/12/11.
 */
import React,{PureComponent} from 'react';
import moment from 'moment';
import { connect } from 'dva';
import { Table, Card, Button ,Form ,Input ,Row ,Col ,Select ,Popconfirm ,Modal ,message ,Divider} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from '../TableList.less';
import {listParams,productStatus,productType} from '../defaultData';
import {findObjByKey ,convertLongToString} from '../../utils/index'
const FormItem = Form.Item;
const { Option } = Select;
@connect(state=>({
  product:state.product
}))
@Form.create()
export default class extends PureComponent{
  state={
    pagination:{
      ...listParams,
    },
    isvisible:false,
    editObj:{},
    key:Math.random()
  }
  defaultData={
    name:'',
    template:'',
    remark:'',
    content:'',
    type:productType[0].key,
    state:productStatus[0].key
  }
  columns=[{
    title: '产品名称',
    dataIndex: 'name',
  },{
    title: '产品类型',
    dataIndex: 'type',
    render:(type)=>{
      let obj = findObjByKey(productType,type,"key");
      return obj ? obj.name : "未知"
    }
  },{
    title: '产品状态',
    dataIndex: 'state',
    render:(state)=>{
      let obj = findObjByKey(productStatus,state,"key");
      return obj ? obj.name : "未知"
    }
  },{
    title: '合同模板',
    dataIndex: 'template'
  },{
    title: '合同内容',
    dataIndex: 'content'
  },{
    title: '备注',
    dataIndex: 'remark'
  },{
    title: "操作",
    dataIndex: "id",
    render: (id,record) =>
      <div className="operations">
        <a onClick={this.showDetail.bind(this,record)}>编辑</a>
        <Divider type="vertical" />
        <Popconfirm title="确认要删除该产品?" onConfirm={this.remove.bind(this,record.id)}><a>删除</a></Popconfirm>
      </div>
  }];
  showDetail=(params={})=>{
    //this.props.form.setFieldsValue(params);
    this.setState({
      editObj:{...params},
      isvisible:true,
      key:Math.random()
    })

  }
  remove=(id)=>{
    let _this=this;
    this.props.dispatch({
      type:'product/fetchRemove',
      payload:{id}
    }).then(jsonData=>{
      if(jsonData.result){
        message.success('删除成功',0.8,()=>{
          _this.getList();
        })
      }else{
        message.error(jsonData.msg);
      }
    })
  }
  submit=()=>{
    let _this=this;
    this.props.form.validateFieldsAndScroll((err,values)=>{
      if(!err){
        let params={};
        for(var i in values){
          if(i.indexOf('search')<0){
            params[i]=values[i];
          }
        }
        let editObj=Object.assign({},this.state.editObj,params);
        let patchType='product/fetchAdd';
        if(editObj.id){
          patchType='product/fetchEdit'
        }
        this.props.dispatch({
          type:patchType,
          payload:editObj
        }).then(jsonData=>{
          if(jsonData.result){
            message.success(`${editObj.id?'修改':'添加'}成功`,0.8,()=>{
              _this.handleCancel();
              _this.getList();
            })

          }else{
            message.error(jsonData.msg)
          }
        });
      }
    })

  }
  handleCancel=()=>{
    this.setState({
      isvisible:false
    })
  }

  handleSearch=(e)=>{
    e.preventDefault();
    let values=this.props.form.getFieldsValue();
    let params={};
    for(var i in values){
      if(i.indexOf('search')>=0){
        let index=i.toLowerCase().replace('search','');
        params[index]=values[i];
      }
    }
    params.current=1;
    this.setState({
      pagination:Object.assign(this.state.pagination,params)
    },()=>{
      this.getList();
    })
  }

  getList=(page={current:1})=>{
    let pagination=this.state.pagination;
    this.props.dispatch({
      type:'product/fetchList',
      payload:Object.assign({},pagination,page)
    })
  }
  renderForm=()=>{
    const { getFieldDecorator } = this.props.form;
    return (<Form onSubmit={this.handleSearch} layout="inline">
      <Row gutter={{ md: 8, lg: 15, xl: 15 }}>
        <Col md={6}>
          <FormItem label="产品名称" >
            {getFieldDecorator('searchName')(
              <Input placeholder="请输入产品名称" />
            )}
          </FormItem>
        </Col>
        <Col md={6}>
          <FormItem label="合同模板">
            {getFieldDecorator('searchTemplate')(
              <Input placeholder="请输入合同模板" />
            )}
          </FormItem>
        </Col>
        <Col md={5}>
          <FormItem label="产品状态">
            {getFieldDecorator('searchState')(
              <Select placeholder="请选择" style={{ width: '100%' }}>
                <Option value={null}>请选择</Option>
                {
                  productStatus.map(item=><Option key={item.key} value={item.key}>{item.name}</Option>)
                }
              </Select>
            )}
          </FormItem>
        </Col>
        <Col md={5} sm={10}>
          <FormItem label="产品类型">
            {getFieldDecorator('searchType')(
              <Select placeholder="请选择" style={{ width: '100%' }}>
                <Option value={null}>请选择</Option>
                {
                  productType.map(item=><Option key={item.key} value={item.key}>{item.name}</Option>)
                }
              </Select>
            )}
          </FormItem>
        </Col>
        <Col md={1} sm={24}>
          <FormItem >
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">查询</Button>
            </span>
          </FormItem>
        </Col>
      </Row>
    </Form>)
  }

  componentDidMount(){
    this.getList();
  }
  render(){
    let {getFieldDecorator} = this.props.form;
    let {editObj}= this.state;
    return (<PageHeaderLayout title="产品管理" >
      <Card bordered={false}>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>
            {this.renderForm()}
          </div>
          <div className={styles.tableListOperator}>
            <Button icon="plus" type="primary" onClick={this.showDetail.bind(this,this.defaultData)}>
              新增产品
            </Button>
          </div>
          <div style={{marginTop: 20}}>
            <Table rowKey="id"
                   loading={this.props.product.loading}
                   columns={this.columns}
                   pagination={{...this.state.pagination,total:this.props.product.total}}
                   dataSource={this.props.product.productList}
                   onChange={this.getList}
            />
          </div>
        </div>
      </Card>
      <Modal title={editObj.id ? "编辑产品":"新增产品"}
             onOk={this.submit}
             onCancel={this.handleCancel}
             visible={this.state.isvisible}
             key={this.state.key}
      >
        <Form ref="productForm" className={styles.modal}>
          <div className="flex-row">
            <div className="flex1">
              <FormItem label="产品名称">
                {getFieldDecorator('name', {
                  initialValue:editObj.name || '',
                  rules: [{
                    required: true, message: '请输入产品名称'
                  }],
                })(
                  <Input placeholder='请输入产品名称' style={{width:"80%"}}  />
                )}
              </FormItem>
            </div>
            <div className="flex1">
              <FormItem label="合同模板">
                {getFieldDecorator('template',{
                  initialValue:editObj.template || '',
                })(
                  <Input placeholder='请输入合同模板' style={{width:"80%"}}/>
                )}
              </FormItem>
            </div>
          </div>
          <div className="flex-row">
            <div className="flex1">
              <FormItem label="产品类型">
                {getFieldDecorator('type',{
                  initialValue: editObj.type || productType[0].key,
                  rules:[{
                    required:true,
                    message:'请选择产品类型'
                  }]
                })(
                  <Select style={{width:"80%"}}>
                    {productType.map(item=><Option key={item.key} value={item.key}>{item.name}</Option>)}
                  </Select>
                )}
              </FormItem>
            </div>
            <div className="flex1">
              <FormItem label="产品状态">
                {getFieldDecorator('state',{
                  initialValue: editObj.state || productStatus[0].key,
                  rules:[{
                    required:true,
                    message:'请选择产品状态'
                  }]
                })(
                  <Select style={{width:"80%"}}>
                    {productStatus.map(item=><Option key={item.key} value={item.key}>{item.name}</Option>)}
                  </Select>
                )}
              </FormItem>
            </div>
          </div>
          <FormItem label="产品内容">
            {getFieldDecorator('content',{
              initialValue:editObj.content || '',
            })(
              <Input.TextArea placeholder='请输入产品内容'  style={{height:"70px"}}  />
            )}
          </FormItem>
          <FormItem label="备注">
            {getFieldDecorator('remark',{
              initialValue:editObj.remark || '',
            })(
              <Input.TextArea placeholder='请输入产品备注' style={{height:"70px"}}  />
            )}
          </FormItem>
        </Form>
      </Modal>
    </PageHeaderLayout>)
  }
}
